package com.tbit.main.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 导出excel
 *
 * @author Leon
 * 2013-1-17 下午05:12:27
 */
@Slf4j
public class ExportExcelUtils {

    /**
     * http下载excel文件
     *
     * @param response
     * @param fileName
     * @param values
     */
    public static void exportExcel(HttpServletResponse response, String fileName, List<String[]> values) {
        /** 头设置 */
        response.setContentType("application/ms-excel");
        try {
            /** gb2312才能兼容所有浏览器 */
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xls");
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        }
        response.setCharacterEncoding("UTF-8");

        try {
            // 创建工作薄
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 创建工作表
            HSSFSheet sheet = workbook.createSheet("data");

            for (int row = 0; row < values.size(); row++) {
                /** 行数 */
                HSSFRow rows = sheet.createRow(row);
                /** 列内容 */
                String[] line = values.get(row);
                for (int col = 0; col < line.length; col++) {
                    // 向工作表中添加数据
                    rows.createCell(col).setCellValue(line[col]);
                }
            }

            /** 调整自动适应宽度 */
            int cols = values.get(0).length;
            for (int i = 0; i < cols; i++) {
                sheet.autoSizeColumn(i);
            }

            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
